// websocket-plugin.js
import WebSocketService from './services/WebSocketService.js';

const WebSocketPlugin = {
    install(app) { // 注意这里使用 app 而不是 Vue
        const url = 'ws://localhost:8001/ws'; // WebSocket服务器的URL
        const websocket = new WebSocketService(url);
        // 添加 sendMessage 方法
        websocket.sendMessage = (message) => {
            if (websocket.socket) {
                websocket.socket.send(message);
            }
        };
        // 断开连接
        websocket.disconnect = () => {
            if (websocket.socket) {
                websocket.socket.close();
                console.log("断开了1链接")
            }
        };
        // 添加一个用于监听消息的方法
        websocket.addMessageListener = (callback) => {
            if (websocket.socket) {
                websocket.socket.addEventListener('message', (event) => {
                    const message = event.data;
                    console.log("Received message:", message); // 打印消息内容
                    callback(message); // 调用回调函数来处理接收的消息
                });
            }
        };

        app.config.globalProperties.$websocket = websocket; // 使用 app.config.globalProperties 来设置全局属性
    },
};

export default WebSocketPlugin;
